<template>
  <div class="profile-page">
    <div class="profile-container">
      <!-- 个人信息卡片 -->
      <el-card class="profile-card info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h2>个人主页</h2>
            <p class="subtitle">您的账号信息</p>
            <el-button type="primary" @click="showEditDialog" class="edit-button">编辑资料</el-button>
          </div>
        </template>
        <div class="user-info">
          <el-descriptions :column="1" border v-if="user" class="user-descriptions">
            <el-descriptions-item label="ID">
              <span class="info-text">{{ user.id }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="电子邮件">
              <span class="info-text">{{ user.email }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="用户名">
              <span class="info-text">{{ user.username }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="性别">
              <span class="info-text">{{ user.gender || '未设置' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="年龄">
              <span class="info-text">{{ user.age || '未设置' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="注册时间">
              <span class="info-text">{{ formatDate(user.register_time) }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="用户简介">
              <span class="info-text">{{ user.bio || '暂无简介' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="最后登录时间">
              <span class="info-text">{{ user.last_login ? formatDate(user.last_login) : '从未登录' }}</span>
            </el-descriptions-item>
          </el-descriptions>
          <div v-if="!user" class="loading-container">
            <el-icon class="loading-icon" :size="24">
              <Loading />
            </el-icon>
            <p class="loading-text">用户信息加载中...</p>
          </div>
        </div>
      </el-card>

      <!-- 帖子列表卡片 -->
      <el-card class="profile-card posts-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3>我的帖子</h3>
          </div>
        </template>
        <div class="posts-section">
          <el-table
            :data="userPosts"
            style="width: 100%"
            v-loading="loadingPosts"
            class="posts-table"
          >
            <el-table-column
              prop="title"
              label="标题"
              min-width="200"
              show-overflow-tooltip
            >
              <template #default="scope">
                <router-link :to="`/tiezi/${scope.row.id}`" class="post-title-link">
                  {{ scope.row.title }}
                </router-link>
              </template>
            </el-table-column>
            <el-table-column
              prop="create_time"
              label="发布时间"
              min-width="160"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ formatDate(scope.row.create_time) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="like_num"
              label="点赞数"
              min-width="80"
              align="center"
            />
            <el-table-column
              prop="reply_num"
              label="回复数"
              min-width="80"
              align="center"
            />
          </el-table>
        </div>
      </el-card>
    </div>

    <!-- 编辑个人信息对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑个人信息"
      width="90%"
      max-width="500px"
      :close-on-click-modal="false"
      class="edit-dialog"
    >
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入新的用户名"></el-input>
        </el-form-item>
        <el-form-item label="个人简介" prop="bio">
          <el-input
            v-model="editForm.bio"
            type="textarea"
            :rows="4"
            placeholder="请输入个人简介"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="editForm.gender" placeholder="请选择性别" class="w-full">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="editForm.age" :min="0" :max="150" class="w-full" />
        </el-form-item>
        <el-form-item label="当前密码" prop="current_password">
          <el-input
            v-model="editForm.current_password"
            type="password"
            placeholder="请输入当前密码以验证身份"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { UpdateProfile } from '@/api/auth';
import { GetUserPosts } from '@/api/tiezi';
import { Loading } from '@element-plus/icons-vue';

const user = ref(null);
const dialogVisible = ref(false);
const editFormRef = ref(null);
const loading = ref(false);
const userPosts = ref([]);
const loadingPosts = ref(false);

const editForm = ref({
  username: '',
  bio: '',
  gender: '',
  age: null,
  current_password: ''
});

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  current_password: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  age: [{ type: 'number', message: '年龄必须为数字', trigger: 'blur' }]
};

const GetUserinfo = () => {
    try {
        const userInfo = localStorage.getItem('user_info');
        if (userInfo) {
            user.value = JSON.parse(userInfo);
            console.log(user.value);
            // 获取用户帖子
            fetchUserPosts();
        } else {
            console.warn('No user information found in localStorage.');
        }
    } catch (error) {
        console.error('Error parsing user information:', error);
    }
};

// 获取用户发布的帖子
const fetchUserPosts = async () => {
  if (!user.value || !user.value.id) return;
  
  loadingPosts.value = true;
  try {
    const response = await GetUserPosts(user.value.id);
    if (response.data.code === 200) {
      userPosts.value = response.data.data || [];
    } else {
      console.error('获取用户帖子失败:', response.data.message);
      ElMessage.error(response.data.message || '获取用户帖子失败');
    }
  } catch (error) {
    console.error('获取用户帖子出错:', error);
    ElMessage.error('获取用户帖子失败');
  } finally {
    loadingPosts.value = false;
  }
};

const showEditDialog = () => {
  editForm.value.username = user.value.username;
  editForm.value.bio = user.value.bio || '';
  editForm.value.gender = user.value.gender || '';
  editForm.value.age = user.value.age || null;
  editForm.value.current_password = '';
  dialogVisible.value = true;
};

const submitForm = async () => {
  if (!editFormRef.value) return;

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const response = await UpdateProfile(editForm.value);
        if (response.data.code === 200) {
          ElMessage.success('个人信息更新成功');
          // 更新本地存储的用户信息
          const userInfo = JSON.parse(localStorage.getItem('user_info'));
          userInfo.username = editForm.value.username;
          userInfo.bio = editForm.value.bio;
          userInfo.gender = editForm.value.gender;
          userInfo.age = editForm.value.age;
          localStorage.setItem('user_info', JSON.stringify(userInfo));
          // 更新页面显示的用户信息
          user.value = userInfo;
          dialogVisible.value = false;
          // 刷新用户帖子列表
          fetchUserPosts();
        } else {
          ElMessage.error(response.data.msg || '更新失败');
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.msg || '更新失败');
      } finally {
        loading.value = false;
      }
    }
  });
};

onMounted(() => {
    GetUserinfo();
});

const formatDate = (dateString) => {
    const date = new Date(dateString);

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，+1调整
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 2rem 1rem;
  box-sizing: border-box;
}

.profile-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 2rem;
  align-items: start;
}

.profile-card {
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.profile-card:hover {
  transform: translateY(-5px);
}

.info-card {
  height: fit-content;
}

.posts-card {
  height: fit-content;
}

.card-header {
  text-align: center;
  padding: 1.5rem 1rem;
  position: relative;
  border-bottom: 1px solid #eee;
}

.card-header h2,
.card-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.5rem;
  font-weight: 600;
}

.subtitle {
  margin: 0.5rem 0 0;
  color: #7f8c8d;
  font-size: 0.875rem;
}

.edit-button {
  position: absolute;
  right: 1rem;
  top: 50%;
  transform: translateY(-50%);
}

.user-info {
  padding: 1.5rem;
}

.user-descriptions {
  transition: all 0.3s ease;
}

:deep(.el-descriptions__cell) {
  padding: 1rem;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  color: #34495e;
  min-width: 120px;
}

.info-text {
  color: #2c3e50;
  font-size: 0.875rem;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 2rem 0;
}

.loading-icon {
  color: #4CAF50;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.posts-section {
  padding: 0 1rem;
}

.posts-table {
  margin-top: 1rem;
}

.post-title-link {
  color: #409EFF;
  text-decoration: none;
  transition: color 0.3s;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.post-title-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.edit-dialog {
  :deep(.el-dialog) {
    margin: 1rem !important;
  }

  :deep(.el-select),
  :deep(.el-input-number) {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .profile-container {
    grid-template-columns: 1fr;
  }

  .card-header {
    padding: 1rem;
  }

  .edit-button {
    position: static;
    transform: none;
    margin-top: 1rem;
    width: 100%;
  }

  .user-info {
    padding: 1rem;
  }

  :deep(.el-descriptions__cell) {
    padding: 0.75rem;
  }

  .posts-section {
    padding: 0 0.5rem;
  }

  .dialog-footer {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;

    .el-button {
      width: 100%;
    }
  }
}
</style>